import { Switch } from 'antd'
import { useState } from 'react'

import { getAppState } from '@/utils/dvaUtil/index'

/**
 * @typedef {Object} OtherProps
 * @property {() => Promise} [onSubmit] 提交
 * @property {string} [permissionKey] 权限值
 */

/**
 * @typedef {import("antd/es/switch").SwitchProps & OtherProps} AekSwitchProps
 */

/**
 * @param {AekSwitchProps} props
 * @returns
 */
const AekSwitch = props => {
  const [loading, setLoading] = useState(false)
  const {
    permissionKey,
    onClick: propOnClick,
    onSubmit,
    defaultChecked,
    checkedChildren,
    unCheckedChildren,
    ...other
  } = props

  const { loginInfo } = getAppState()

  const onClick = async e => {
    propOnClick?.(e)
    if (!onSubmit) return
    setLoading(true)
    await onSubmit(e).finally(() => {
      setLoading(false)
    })
  }

  return loginInfo.authorization.authorities.includes(permissionKey) || !permissionKey ? (
    <Switch
      {...{
        defaultChecked,
        checkedChildren,
        unCheckedChildren,
        ...other,
      }}
      loading={loading}
      onClick={onClick}
    />
  ) : defaultChecked ? (
    checkedChildren
  ) : (
    unCheckedChildren
  )
}

export default AekSwitch
